--^^^^^^^^^^^^^^^^^^^^^^^^^^--
--By Tran Anh Tuan
--Date: 07/2011
--Email: tatuanvn@gmail.com
--Skype: trananhtuan_huecit
--Mobi: (+84)054.982.951.555
--=========================--
module(..., package.seeall)

directorView = display.newGroup()
currentView  = display.newGroup()
nextView     = display.newGroup()
effectView   = display.newGroup()

local currentScreen, nextScreen
lastScene = "main"
local newScene = "main"

directorView:insert(currentView)
directorView:insert(nextView)
directorView:insert(effectView)
-----------------------------------
-- 
-----------------------------------
local function loadScene (nextScene, sound)
	if string.lower(nextScene) ~= "main" then
		nextScreen = require(nextScene).new(sound)
		nextView:insert(nextScreen)
    end
end
-----------------------------------
-- 
-----------------------------------
local function cleanGroups ( curGroup, level )
    if curGroup.numChildren then
        while curGroup.numChildren > 0 do
            cleanGroups ( curGroup[curGroup.numChildren], level+1 )
        end
        if level > 0 then
            curGroup:removeSelf()
			curGroup = nil
        end
    else
        curGroup:removeSelf()
        curGroup = nil
        return
    end
end
-----------------------------------
-- 
-----------------------------------
local function fxEnded ( event )
 
    currentView.x = 0
    currentView.y = 0
    currentView.xScale = 1
    currentView.yScale = 1
    --
    cleanGroups(currentView, 0)
    --
    currentScreen = nextScreen
    currentView:insert(currentScreen)
    nextView.x = display.contentWidth
    nextView.y = 0
    nextView.xScale = 1
    nextView.yScale = 1
    
    -----------------------------------
    -- Clean up memory
    -----------------------------------
    
    if lastScene then
          -- Custom clean function (unloadMe)
         if string.lower(lastScene) ~= "main" then
            package.loaded[lastScene].unloadMe()
         end
            package.loaded[lastScene] = nil
    end
    timer.performWithDelay(1, function() collectgarbage("collect") end)        
end
-----------------------------------
-- 
-----------------------------------
function director:changeScene(nextScene, sound)
	timer.performWithDelay( 0, fxEnded )
	lastScene = newScene
	newScene = nextScene
	loadScene (nextScene, sound)
	return true
end